package net.app.zoneland.search.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import net.app.zoneland.common.core.vo.Result;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2021/2/14 10:03
 * @Version: 1.0
 */
public abstract class BaseController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @ApiOperation(value = "判断索引是否存在接口", notes = "判断索引是否存在接口")
    @RequestMapping(value = "/index/exists", method = RequestMethod.POST)
    protected boolean indexExists(@RequestParam String indexName){
        try {
            GetIndexRequest request = new GetIndexRequest(indexName);
            IndicesClient indices = restHighLevelClient.indices();
            boolean exists = indices.exists(request, RequestOptions.DEFAULT);
            return exists;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @ApiOperation(value = "删除索引接口", notes = "es删除索引接口")
    @RequestMapping(value = "/delete/index/{indexName}", method = RequestMethod.POST)
    public Result deleteIndex(@RequestParam("indexName") String indexName) {
         if(indexExists(indexName)){
             DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
             //操作索引的客户端
             IndicesClient indices = restHighLevelClient.indices();
             try{
                 //执行删除
                 AcknowledgedResponse deleteIndexResponse = indices.delete(deleteIndexRequest,RequestOptions.DEFAULT);

                 //得到响应
                 boolean acknowledged = deleteIndexResponse.isAcknowledged();
                 return Result.success(acknowledged);
             }catch (Exception e){
                 e.printStackTrace();
             }
         }
        return Result.error("索引库不存在或删除出错啦！");
    }

    /**
     * 修改数据
     *
     * @param index      索引名称
     * @param type       类型
     * @param jsonObject json对象(要添加的数据)
     * @param id
     * @return RestStatus ok
     */
    public Result updateDoc(String index, String type, JSONObject jsonObject, String id) {
        try {
            // 索引响应对象
            UpdateRequest updateRequest = new UpdateRequest(index,type);
            updateRequest.doc(jsonObject, XContentType.JSON);
            updateRequest.id(id);
            restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            return Result.success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("更新失败");
    }

    // 设置高亮字段
    protected HighlightBuilder getHighlightBuilder(String... fields) {
        // 高亮条件
        HighlightBuilder highlightBuilder = new HighlightBuilder(); //生成高亮查询器
        for (String field : fields) {
            highlightBuilder.field(field);//高亮查询字段
        }
        highlightBuilder.requireFieldMatch(false);     //如果要多个字段高亮,这项要为false
        highlightBuilder.preTags("<span style=\"color:red\">");   //高亮设置
        highlightBuilder.postTags("</span>");
        //下面这两项,如果你要高亮如文字内容等有很多字的字段,必须配置,不然会导致高亮不全,文章内容缺失等
        highlightBuilder.fragmentSize(800000); //最大高亮分片数
        highlightBuilder.numOfFragments(0); //从第一个分片获取高亮片段

        return highlightBuilder;
    }

}
